import axios from 'axios'
import router from './routes'

const service = axios.create({
    baseURL: process.env.MIX_VUE_APP_API_BASE_URL,
    timeout: 10000
});
service.interceptors.request.use(
    config => {
        config.headers["Content-Type"] = "application/json";
        return config;
    },
    error => {
        Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
        const res = response;
        // return res
        if (res.status !== 200) {
            // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
            if (res.status === 401 || res.status === 402 || res.status === 407) {
                router.push("/login")
            } else if (res.status === 403) {
                router.push("/403")
            }
            return Promise.reject("error")
        } else {
            return response.data
        }
    },
    err => {
        if (err && err.response) {
            switch (err.response.status) {
                case 400:
                    break;
                case 401:
                    router.push("/login");
                    break;
                case 403:
                    break;
                case 404:
                    break;
                case 408:
                    break;
                case 500:
                    break;
                case 501:
                    break;
                case 502:
                    break;
                case 503:
                    break;
                case 504:
                    break;
                default:
                    ''
            }
        }
        return Promise.reject(err);
    }
)

export default service
